package com.yungam.other.iot_controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.yungam.common.bean.equip.Equipment;
import com.yungam.common.bean.equip.EquipmentConfig;
import com.yungam.common.response.RetDTO;
import com.yungam.common.service.EquipmentConfigService;
import com.yungam.common.service.EquipmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 设备同步
 */
@Slf4j
@RestController
@RequestMapping("/imcs_to_iot")
public class UpdateEquipsController {

    @Resource
    private EquipmentService equipmentService;
    @Resource
    private EquipmentConfigService equipmentConfigService;

    @PostMapping("/updateEquips")
    public RetDTO<?> updateEquips(@RequestBody Map<Integer, Map<String, Object>> data) {
        log.info("========= START『iot调用imcs』[更新设备接口] =========");
        String json = new Gson().toJson(data);
        log.info("=========『iot数据』{}", json);
        if (data.keySet().size() == 0) {
            log.error("=========『设备数据为空』=========");
            return RetDTO.error("设备为空");
        }

        // 更新设备信息 & 更新参数配置信息
        QueryWrapper<Equipment> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(Equipment.class, col -> !col.getProperty().equals("equImg"));
        List<Equipment> list = equipmentService.list(queryWrapper);
        List<EquipmentConfig> configList = Lists.newArrayList();
        for (Equipment equipment : list) {
            Map<String, Object> map = data.get(equipment.getEquId());
            if (map == null) continue;
            equipment.setEquIp(String.valueOf(map.get("ip")));
            equipment.setEquName(String.valueOf(map.get("name")));
            equipmentService.updateById(equipment);

            List<Map<String, Object>> items = (List<Map<String, Object>>) map.get("items");
            equipmentConfigService.remove(new QueryWrapper<EquipmentConfig>().eq("equ_id", equipment.getEquId()));
            for (Map<String, Object> item : items) {
                EquipmentConfig ec = new EquipmentConfig();
                ec.setItemId((Integer) item.get("itemId"));
                ec.setEquId(equipment.getEquId());
                ec.setDataContent((String) item.get("name"));
                ec.setDataType((String) item.get("type"));
                ec.setUnit((String) item.get("unit"));
                configList.add(ec);
            }
        }
        equipmentConfigService.saveBatch(configList);
        log.info("=========== END 更新成功 ===========");
        return RetDTO.success();
    }

}
